package com.andox.fn.inf.rpc.rest.filter;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import com.andox.fn.inf.rpc.rest.RpcRequest;
import com.andox.fn.inf.rpc.rest.RpcResponse;
import com.andox.fn.inf.rpc.rest.common.DefaultValueConcurrentHashMap;
import com.andox.fn.inf.rpc.rest.extension.Extension;

@Extension("ratelimit")
public class RateLimitFilter implements Filter{
	private Map<String, AtomicInteger> counts = new DefaultValueConcurrentHashMap<>(() -> new AtomicInteger(0));
	
	@Override
	public RpcResponse invoke(Invoker nextInvoker, RpcRequest request) {
		try {
			counts.get(request.getMethod()).incrementAndGet();
			return nextInvoker.invoke(request);
		}finally {
			counts.get(request.getMethod()).decrementAndGet();
		}
	}
}
